//获取服务器当前时间
function getNowDate(format) {
	var time = '';
	$.ajax({
		type : "post",
		url : "/common/getNowDate",
		async : false,
		dataType : "json",
		success : function(data){
			time = toDate(data.time,format);
		},
	    error : function() {
	    	BSTYUN.dialog.warn("网络异常，请重试");
			return;
	    }
	})
	return time;
}

var sum = 0;
var dialogData;
var taocan;

//进入页面的 时候的计算
function countAll(){
	var length = $('input[name="checkbox"]:checked').length;
	$('#allnum').html(length);
	countSum();
	formatUseLife();
}

//计算优惠 
function calculateDiscount(id){
	var roleId = $('#loginUserRoleId').val(),
		isValid = $('#isValid').val(),
		mealPrivilege = $('#mealPrivilege').val(),
		proPrivilege = $('#proPrivilege').val(),
		relationId = $('#relationId'+id).val(),
		proMealPrice = $('#proMealPrice'+id).val();
	if(roleId == 'ROLE_AGENT'){
		if(isValid == 1){
			if(relationId == '0'){
				var mp = 1-mealPrivilege;
				proMealPrice = parseFloat(proMealPrice).toFixed(2) * parseFloat(mp).toFixed(2);
				$('#discount'+id).text(parseFloat(proMealPrice * (-1)).toFixed(2));
			}else{
				var pp = 1-proPrivilege;
				proMealPrice = parseFloat(proMealPrice).toFixed(2) * parseFloat(pp).toFixed(2);
				$('#discount'+id).text(parseFloat(proMealPrice * (-1)).toFixed(2));
			}
		}else{
			$('#discount'+id).text('0.00');
		}
	}else{
		$('#discount'+id).text('0.00');
	}
	
}

//将年限重新格式化一下
function formatUseLife(){
	var idList = $('input[name="shoppingCartId"]');
	var lifeList = $('input[name="useLife"]');
	for(var i=0;i<lifeList.length;i++){
		var id = idList[i].value;
		var life = lifeList[i].value;
		if(life == "-1"){
			$('#plusYear'+id).attr("value","∞");
		}else if(life == "0"){
			$('#plusYear'+id).attr("value","20天");
		}
		
	}
}

//sum 总计金额 
function countSum(){
	var checkboxList = $("input[name='checkbox']");
	var priceList = $('.price_line');
	var sum = 0.00,_sum=0.00;
	for(var i=0;i<priceList.length;i++){
		_sum = $('.price_line')[i].innerHTML;
		if(checkboxList[i].checked == true)	sum += parseFloat(_sum);
	}
	
	var offerList = $('.offer');
	for(var i=0;i<offerList.length;i++){
		_sum = $('.offer')[i].innerHTML;
		if(checkboxList[i].checked == true)	sum += parseFloat(_sum);
	}	
	
	$('#allsum').html(parseFloat(sum).toFixed(2));
}

//单选  以及相关的总计
function cancleOther(){
	var checkbox = $("input[name='checkbox']");
	$('input[name="checkboxAll"]').prop("checked",checkbox.length == $("input[name='checkbox']:checked").length ? true : false);
	
	var length = $('input[name="checkbox"]:checked').length;
	$('#allnum').html(length);
	countSum();
}

//计算  userNumber 基数    price  价格      userYear  年限  allsum 总计
function count(id){
	
	var price = $('#goodsPrice'+id).val();
	var num = $('#proMealNum'+id)[0].innerHTML;
	var localPrice = $('#localUseYear'+id).val();
	
	var _userNumer = $('#plusUserNum'+id).val();
	var _userYear = $('#plusYear'+id).val();
	
	if(localPrice == '20天' && _userYear == '20天'){
		 $('#proMealPrice'+id).val('0.00');
		 $('#proMealPrice'+id).html('0.00');
		 return;
	}else if(_userYear == 0){
		$('#proMealPrice'+id).val('0.00');
		 $('#proMealPrice'+id).html('0.00');
		 return;
	}
	
	if(_userYear == "∞") _userYear = 1;
	if(_userYear == "20天") _userYear = 0;
	
	var _price = parseFloat(_userNumer * price * _userYear * num ).toFixed(2) ;
	
	$('#proMealPrice'+id).val(_price);
	$('#proMealPrice'+id).html(_price);
	
}

//年限加号减号触发事件
function plusOrMinusYearNum(code,addend,e,id){
	var addnum = $('#'+e).val();
	var localPrice = $('#localUseYear'+id).val();
	
	if(addnum == '∞'){
		BSTYUN.dialog.warn('年限已最大！');
		return;
	}
	if(code=='plus'){
		if(addnum == '20天'){
			addnum = 0;
			addend == 1;
		}
		addnum = parseInt(addnum) + parseInt(addend);
	}
	else if(code=='minus'){
		if(addnum == '20天'){
			BSTYUN.dialog.warn('此条记录加入购物车时为试用，则最小年限为20天！');
			$('#'+e).val('20天');
			
			count(id);
			return;
		}
		addnum = parseInt(addnum) - parseInt(addend);
	}
	
	if(localPrice == '20天' && parseInt(addnum) < 0 ) {
		BSTYUN.dialog.warn('此条记录加入购物车时为试用，则最小年限为20天！');
		$('#'+e).val('20天');
		
		count(id);
		return;
	}else if(parseInt(addnum) < 1 ){
		BSTYUN.dialog.warn('不能再减啦！最小年限不能为0年！');
		$('#'+e).val(1);
	}else $('#'+e).val(addnum);
	
	rangeValid('userYear',e,id);
	
	count(id);
	
	calculateDiscount(id);
	
	countSum();
}

//用户数量 加号减号触发事件
function plusOrMinusUserNum(code,addend,e,id){
	var addend = $('#'+addend).val();
	var addnum = $('#'+e).val();
	if(code=='plus') addnum = parseInt(addnum) + parseInt(addend);
	else if(code=='minus') addnum = parseInt(addnum) - parseInt(addend);
	
	if(parseInt(addnum) < 10) {
		
		BSTYUN.dialog.warn('不能再减啦！最小用户数量不能为0！');
		$('#'+e).val(10);
	}
	else $('#'+e).val(addnum);
	
	rangeValid('maxUser',e,id);
	
	count(id);
	
	calculateDiscount(id);
	
	countSum();
}

//数量 加号减号触发事件
function plusOrMinusProMealNum(code,addend,e,id){
	var addnum = $('#'+e).val();
	if(code=='plus') addnum = parseInt(addnum) + parseInt(addend);
	else if(code=='minus') addnum = parseInt(addnum) - parseInt(addend);
	
	if(parseInt(addnum) < 0) {}//alert("不能小于0");
	else $('#'+e).val(addnum);
	
	countProduct(id);
}

//数量 变化 导致价格变化
function countProduct(id){
	
	var price = $('#goodsPrice'+id).val();
	var _userYear = $('#plusYear'+id).val();
	var _userNumer = $('#plusUserNum'+id).val();
	var num = $('#proMealNum'+id)[0].innerHTML;
	
	if(_userYear == '20天') _userYear = 0;
	if(_userYear == '∞') _userYear = 1;
	
	var _price = parseFloat(_userNumer / userNumber * price * (_userYear / userYear)  * num).toFixed(2) ;
	$('#proMealPrice'+id).val(_price);
	$('#proMealPrice'+id).html(_price);
}

//验证是否处于最大最小值范围  值 类型 修改的字段 
function rangeValid(type,e,id){
	if(type == "maxUser"){
		var usersMin = $('#usersMin'+id).val();
		var usersMax = $('#usersMax'+id).val();
		var _userNumber = $('#plusUserNum'+id).val();
		if(parseInt(_userNumber) > parseInt(usersMax)) {
			BSTYUN.dialog.warn('不能再加啦！最大数量为'+usersMax+'！');
			$('#plusUserNum'+id).val(usersMax);
		}else if(parseInt(_userNumber) < parseInt(usersMin)) {
			BSTYUN.dialog.warn('不能再减啦！最小数量为'+usersMin+'！');
			$('#plusUserNum'+id).val(usersMin);
		}
	}else if(type == "userYear"){
		var yearsMin = $('#yearsMin'+id).val();
		var yearsMax = $('#yearsMax'+id).val();
		var _userYear = $('#plusYear'+id).val();
		if(parseInt(_userYear) > parseInt(yearsMax)){
			BSTYUN.dialog.warn('不能再加啦！最大年限为'+yearsMax+'年！');
			$('#plusYear'+id).val(yearsMax);
		}else if(parseInt(_userYear) < parseInt(yearsMin)){
			BSTYUN.dialog.warn('不能再减啦！最小年限为'+yearsMin+'年！');
			$('#plusYear'+id).val(yearsMin);
		}
	}
}

//年限验证
function yearNumValid(para,e,id){
	var num = $('#'+e).val();
	if(num == '') BSTYUN.dialog.warn('请输入数字，不能为空！');
	var reg = new RegExp(/^[0-9]*$/); 
	if(reg.exec(num) == null){
		BSTYUN.dialog.warn('请输入整数！');
		$('#'+e).val(0);
	}else{
		rangeValid('userYear',e,id);
		count(id);
	}
}

//用户数量验证userNumber,maxUser, ,'maxUser'+${sc.shoppingCartId},'userYear'+${sc.shoppingCartId}
function userNumValid(para,e,id){
	var num = $('#'+e).val();
	if(num == '') BSTYUN.dialog.warn('请输入数字，不能为空！');
	var _num = num / para;
	var reg = new RegExp(/^[0-9]*$/); 
	if(reg.exec(_num) == null){
		BSTYUN.dialog.warn('请输入10的整倍数！');
		$('#'+e).val(0);
	}else{
		rangeValid('maxUser',e,id);
		count(id);
	}
}

//数量验证
function proMealNumValid(para,e,id){
	var num = $('#'+e).val();
	var reg = new RegExp(/^[0-9]*$/); 
	if(num == '') BSTYUN.dialog.warn('请输入数字，不能为空！');
	if(reg.exec(num) == null){
		BSTYUN.dialog.warn('请输入整数！');
		$('#'+e).val(parseInt(num));
	}
}

//全选 以及相关的总计
$(function(){
	var $input = $(".cart_checkbox").find("input");
	var $checkall = $(".checkboxAll");
	$checkall.on("click",function(){
		var $this = $(this);
		if(!$this.prop("checked")){
			$checkall.eq(0).prop("checked",false);
			$checkall.eq(1).prop("checked",false);
			$input.each(function(){
				var _this = $(this);
				_this.prop("checked",false);
			});
			$('#allnum').html(0);
			$('#allsum').html(0.00);
			
		}else{
			$checkall.eq(0).prop("checked",true);
			$checkall.eq(1).prop("checked",true);
			$input.each(function(){
				var _this = $(this);
				_this.prop("checked",true);
			});
			
//			var length = $("#shoppingCartTable").children("tbody").children("tr").length;
			var length = $('input[name="checkbox"]:checked').length;
			$('#allnum').html(length);
			
			countSum();
		}
	});
});


//购物车中  确认订单时  先判断是否有套餐
function checkOrders(shoppingCartId){
	
	var _useYear = $('#plusYear'+shoppingCartId).val(),
		userNum = $('#plusUserNum'+shoppingCartId).val(),
		price = $.trim($('#proMealPrice'+shoppingCartId).html()),
		goodsPrice = $('#goodsPrice'+shoppingCartId).val(),
		shoppingCartId = $('#shoppingCartId'+shoppingCartId).val(),
		proMealId = $('#proMealId'+shoppingCartId).val(),
		requestURI = $("#requestURI").val(),
		loginUserRoleId = $('#loginUserRoleId').val(),
		pageNum = $('#pageNum').val();
	var useYear = _useYear;
	if(_useYear == '∞') useYear = -1;
	if(_useYear == '20天') useYear = 0;
	
	if(userNum == "0" || _useYear == "0"){
		return BSTYUN.dialog.warn("请选择正确的使用人数和使用年限！");
	}
	$.ajax({
		type : "POST",
		url : "/common/checkLogin",
		async : false,
		dataType: 'json',
		success:function(data) {
			if(data) {
//				if(loginUserRoleId == 'ROLE_COMPANY' ){
//					BSTYUN.dialog.warn("您的账户为企业账户，如果希望购买套餐，请重新注册个人用户！<br><a href='/user/registerWay' style='margin-left: 40px;color: rgb(37, 169, 216);font-size: small;'>点击这里进行注册个人用户！</a>");
//					return;
//				}else if(loginUserRoleId == 'ROLE_PERSON' || loginUserRoleId == 'ROLE_AGENT'){
					$.ajax({
						type:"POST",
						url:"/buy/cartHaveRelation",
						async:false,
						data:{
							shoppingCartId : shoppingCartId,
							useYear : useYear,
							userNum : userNum,
							pageNum : pageNum
						},
						dataType:"json",
						success:function(data,response){
							var orderList = data.orderList;
							var goods = data.goods;
							var goodsVo = data.goodsVo;
							if(data.hasRelation){
								if(loginUserRoleId == 'ROLE_PERSON'){
									if(data.hasBuy){
										if(proMealId == orderList[0].goodsId ){
											BSTYUN.dialog.warn("您已经购买过该商品！");
										}else{
											showMealList(data,useYear,userNum,price,shoppingCartId);
										}
									}else{
										BSTYUN.dialog.warn("该商品依托于"+goods.goodsName+",请先购买"+goods.goodsName+"商品！");
									}
								//代理商用户
								}else if(loginUserRoleId == 'ROLE_AGENT'){
									if(data.hasBuy){
										showMealList(data,useYear,userNum,price,shoppingCartId);
									}else{
										BSTYUN.dialog.warn("该商品依托于"+goods.goodsName+",请先购买"+goods.goodsName+"商品！");
									}
								}else if(loginUserRoleId == 'ROLE_COMPANY'){
									if(data.hasBuy){
										if(data.isBuy ){
											BSTYUN.dialog.warn("您已经购买过该商品！");
										}else{
											showMealList(data,useYear,userNum,price,shoppingCartId);
										}
									}else{
										BSTYUN.dialog.warn("您的账户为企业账户，如果希望购买套餐，请重新注册个人用户！<br><a href='/user/registerWay' style='margin-left: 40px;color: rgb(37, 169, 216);font-size: small;'>点击这里进行注册个人用户！</a>");
									}
								}
								
							}else{
								if(loginUserRoleId == 'ROLE_PERSON'){
									if(data.hasBuy){
										BSTYUN.dialog.warn("您已经购买过该商品！");
									}else{
										location.href="/dredge/"+proMealId+"/"+useYear+"/"+userNum+"/"+shoppingCartId;
									}
								//代理商用户
								}else if(loginUserRoleId == 'ROLE_AGENT'){
									location.href="/dredge/"+proMealId+"/"+useYear+"/"+userNum+"/"+shoppingCartId;
								}else if(loginUserRoleId == 'ROLE_COMPANY'){
									if(data.hasBuy){
										if(data.isBuy ){
											BSTYUN.dialog.warn("您已经购买过该商品！");
										}else{
											showMealList(data,useYear,userNum,price,shoppingCartId);
										}
									}else{
										BSTYUN.dialog.warn("您的账户为企业账户，如果希望购买套餐，请重新注册个人用户！<br><a href='/user/registerWay' style='margin-left: 40px;color: rgb(37, 169, 216);font-size: small;'>点击这里进行注册个人用户！</a>");
									}
								}
							}
						}
					})
//				}
			}else {
				location.href = "/user/login?returnUrl="+requestURI;
			}
		}
	})
}


//弹出套餐列表
function showMealList(data,useYear,userNum,price,shoppingCartId){
	var dialog = null,
	    html = '',
	    callback = null,
	    list = data.orderList,
	    goodsVo = data.goodsVo,
	    pageUseYear = useYear,
	    pageUserNum = userNum,
	    pagePrice = price;
	
	//当前购买商品的使用年限
	var showPageUseYear = pageUseYear;
	if(showPageUseYear == 0) showPageUseYear = "20天";
	else if(showPageUseYear == -1) showPageUseYear = "∞";
	else showPageUseYear = showPageUseYear + "年";
	
	var showPageendTime;//当前购买产品截止日期
	var nowDate = new Date(getNowDate("yyyy-MM-dd"));
	if(useYear == 0) {
		showPageendTime = AddDays(nowDate,20,'day');
		showPageendTime = formatDate(showPageendTime,"yyyy-MM-dd");
	}else{
		showPageendTime = AddDays(nowDate,useYear,'year');
		showPageendTime = formatDate(showPageendTime,"yyyy-MM-dd");
	}
	
	html = '<div class="product_box">';
	html += '<ul class="nav_title cle"><li>订单编号</li><li>套餐名称</li><li>公司名称</li><li>域名</li><li class="special_li">子产品</li><li style="width:60px">使用年限</li><li style="width:60px">使用人数</li></ul>';
	
	for(var i=0;i<list.length;i++){
		//格式化订单的使用年限
		var useLife = list[i].useLife;
		if(useLife == "-1") useLife = "∞";
		
		//计算该订单的可使用的剩余时间
		var newDate = new Date(getNowDate("yyyy-MM-dd"));;
		var orderOverTime = list[i].overTime,
			orderOverTime = new Date(orderOverTime),
			orderOverTime = calculateMonth(newDate,orderOverTime,'returnDate');
		var year = '',month = '',day = '';
		if(getYear(orderOverTime).year != 0) year = getYear(orderOverTime).year + '年' ;
		if(getYear(orderOverTime).month != 0) month = getYear(orderOverTime).month + '月';
		if(getYear(orderOverTime).day != 0) day = getYear(orderOverTime).day + '天';
		var overTime = year + month + day;
		
		//计算所购买的商品的实际能购买的最大用户数和最大使用年限和截止日期和价格
		//人数
		var dialogUserNum = pageUserNum;
		if(pageUserNum > list[i].userNum){
			dialogUserNum = list[i].userNum;
		}
		//使用年限
		var dialogUseYear = pageUseYear;//所选择年限
		var dialogPrice = 0.00;//价格
		var dialogEndTime;//
		var orderUseLife = list[i].useLife;//该订单的使用年限
		if(orderUseLife == '20天'){//商品为免费
			if(20 > getYear(orderOverTime).day){
				dialogUseYear = getYear(orderOverTime).day + '天';
				dialogPrice = 0.00;
				dialogEndTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),getYear(orderOverTime).day,"day");
				dialogEndTime = formatDate(new Date(dialogEndTime),"yyyy-MM-dd");
			}else{
				dialogUseYear = '20天';
				dialogPrice = 0.00;
				dialogEndTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),20,"day");
				dialogEndTime = formatDate(new Date(dialogEndTime),"yyyy-MM-dd");
			}
		}else if(orderUseLife == '-1'){//商品为永久
			if(dialogUseYear == '0') {
				dialogUseYear = '20天' ;
				dialogPrice = 0.00;
				dialogEndTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),20,"day");
				dialogEndTime = formatDate(new Date(dialogEndTime),"yyyy-MM-dd");
			}else if(dialogUseYear == '∞') {
				dialogUseYear = '∞' ;
				dialogPrice = pagePrice;
				dialogEndTime = '永久';
			}else {
				dialogUseYear = dialogUseYear + '年' ;
				dialogPrice = pagePrice / userNum * dialogUserNum; 
				dialogEndTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),pageUseYear,"year");
				dialogEndTime = formatDate(new Date(dialogEndTime),"yyyy-MM-dd");
			}
		}else{//商品为正常
			newDate = formatDate(newDate,"yyyy-MM-dd");
			//该订单的到期时间
			var orderExcessTime = list[i].overTime;
			orderExcessTime = formatDate(new Date(orderExcessTime),"yyyy-MM-dd");
			orderExcessTime = DateDiff(newDate,orderExcessTime);
			//所选择的商品剩余时间
			var dialogExcessTime;
			if(dialogUseYear == '0') {
				dialogExcessTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),20,"day");
				dialogExcessTime = formatDate(new Date(dialogExcessTime),"yyyy-MM-dd");
				dialogExcessTime = DateDiff(newDate,dialogExcessTime);
				//比较大小
				if(dialogExcessTime < orderExcessTime)dialogExcessTime = dialogExcessTime;
				else dialogExcessTime = orderExcessTime;
				//转换成几年几月几天，界面显示
				dialogExcessTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),20,"day");
				dialogExcessTime = calculateMonth(new Date(getNowDate("yyyy-MM-dd")),dialogExcessTime,'returnDate');
				var year = '',month = '',day = '';
				if(getYear(dialogExcessTime).year != 0) year = getYear(dialogExcessTime).year + '年' ;
				if(getYear(dialogExcessTime).month != 0) month = getYear(dialogExcessTime).month + '月';
				if(getYear(dialogExcessTime).day != 0) day = getYear(dialogExcessTime).day + '天';
				dialogUseYear = year + month + day;
				//截止日期
				dialogEndTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),getYear(dialogExcessTime).day,"day");
				dialogEndTime = formatDate(new Date(dialogEndTime),"yyyy-MM-dd");
				//价格计算
				dialogPrice = 0.00;
			}else if(dialogUseYear == '∞') {
				dialogUseYear = calculateMonth(new Date(getNowDate("yyyy-MM-dd")),orderExcessTime,'returnDate');
				//转换成几年几月几天，界面显示
				var year = '',month = '',day = '';
				if(getYear(dialogUseYear).year != 0) year = getYear(dialogUseYear).year + '年' ;
				if(getYear(dialogUseYear).month != 0) month = getYear(dialogUseYear).month + '月';
				if(getYear(dialogUseYear).day != 0) day = getYear(dialogUseYear).day + '天';
				dialogUseYear = year + month + day;
				//截止日期
				dialogEndTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),orderExcessTime,"day");
				dialogEndTime = formatDate(new Date(dialogEndTime),"yyyy-MM-dd");
				//价格计算
				dialogPrice = pagePrice / userNum * dialogUserNum;
			}else {
				dialogExcessTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),dialogUseYear,"year");
				dialogExcessTime = formatDate(new Date(dialogExcessTime),"yyyy-MM-dd");
				dialogExcessTime = DateDiff(newDate,dialogExcessTime);
				//比较大小
				if(dialogExcessTime < orderExcessTime)dialogExcessTime = dialogExcessTime;
				else dialogExcessTime = orderExcessTime;
				//转换成几年几月几天，界面显示
				dialogUseYear = AddDays(new Date(getNowDate("yyyy-MM-dd")),dialogExcessTime,"day");
				var returnMonth = calculateMonth(new Date(getNowDate("yyyy-MM-dd")),dialogUseYear,'returnMonth');
				dialogUseYear = calculateMonth(new Date(getNowDate("yyyy-MM-dd")),dialogUseYear,'returnDate');
				
				var year = '',month = '',day = '';
				if(getYear(dialogUseYear).year != 0) year = getYear(dialogUseYear).year + '年' ;
				if(getYear(dialogUseYear).month != 0) month = getYear(dialogUseYear).month + '月';
				if(getYear(dialogUseYear).day != 0) day = getYear(dialogUseYear).day + '天';
				dialogUseYear = year + month + day;
				//截止日期
				dialogEndTime = AddDays(new Date(getNowDate("yyyy-MM-dd")),dialogExcessTime,"day");
				dialogEndTime = formatDate(new Date(dialogEndTime),"yyyy-MM-dd");
				//价格计算
				dialogPrice = price / userNum / useYear / 12 * returnMonth * dialogUserNum;
			}
			
			
		}
		
		
		html += '<dl><dt class="product_inforbox"><ul class="cle">';
		html += '<li class="choose_pro"><input type="radio" name="choose_pro"></li>';
		html += '<input type="hidden"  name ="orderId" id="orderId'+list[i].orderId+'" value="'+list[i].orderId+'" />';
		html += '<input type="hidden"  name ="relationId" id="relationId'+list[i].orderId+'" value="'+list[i].goodsId+'" />';
		html += '<input type="hidden"  name ="userId" id="userId'+list[i].orderId+'" value="'+list[i].userId+'" />';
		html += '<input type="hidden"  name ="shoppingCartId" id="shoppingCartId'+shoppingCartId+'" value="'+shoppingCartId+'" />';
		html += '<input type="hidden"  name ="goodsNums" id="goodsNums'+list[i].orderId+'" value="'+list[i].goodsNums+'" />';
		html += '<li><span>'+list[i].orderNum+'</span></li>';
		html += '<li><span>'+list[i].goodsName+'</span></li>';
		html += '<li><span>'+list[i].belongCompanyName+'</span></li>';
		html += '<li><span>'+list[i].companyDomainName+'</span></li>';
		html += '<li class="special_li"><span>'+list[i].goodsNames+'</span></li><li style="width:60px"><span>'+useLife+'</span></li><li style="width:60px"><span>'+list[i].userNum+'</span></li>';
		html += '<li class="lookfor_detail"><a href="/consume/order/order_detail?orderId='+list[i].orderId+'" target="_blank">查看详情</a></li>';
		html += '</ul></dt>';   
		html += '<dd class="product_detail"><div><h4>您所选套餐为'+list[i].goodsName+'，最大使用人数为'+list[i].userNum+'人，截止当前时间，使用年限剩余'+overTime+'</h4>';
		html += '<dl><dt>选择该套餐后，您所购买的产品：</dt><table><tbody><tr><td></td><td>产品名称</td><td>用户数量</td><td>使用年限</td><td>截止日期</td><td>单价</td><td>原价</td></tr>';
	    html += '<tr><td>当前购买</td><td>'+goodsVo.goodsName+'</td><td>'+pageUserNum+'</td><td>'+showPageUseYear+'</td><td>'+showPageendTime+'</td><td>'+goodsVo.goodsPrice+'</td><td>'+pagePrice+'</td></tr>';
	    html += '<tr><td>实际购买</td><td>'+goodsVo.goodsName+'</td><td>'+dialogUserNum+'</td><td>'+dialogUseYear+'</td><td>'+dialogEndTime+'</td><td>'+goodsVo.goodsPrice+'</td><td>'+parseFloat(dialogPrice).toFixed(2)+'</td></tr></tbody></table></dl>';
		html += '<p style="color:red">确定请点击“去支付”按钮。';
		html += '<a href="javascript:void(0);" class="goto_pay" onclick="gotoPay(\''+goodsVo.goodsId+'\','+useYear+','+userNum+','+list[i].orderId+','+list[i].userId+','+shoppingCartId+')">去支付</a></p></div></dd>';
	}

	html += '<div class="page_control"><span></span></div></div>';
	dialog = BSTYUN.dialog.creat({
	  id:'gouwuche',
	  title: '',
	  content:html,
	  init:function(){
		var $content = this.DOM.content,
			$box = $content.find('.product_box'),
	        $inforbox = $box.find('.product_inforbox'),
	        $radio = $box.find('.choose_pro input'),
	        $detail = $box.find('.product_detail'),
	        $page = $box.find('.page_control span'),
	        element = 1,  //分子，当前页数,默认第一页
	        denominator = Math.ceil($inforbox.size()/3),//分母，总页数
	        page_html = '';
	    /*调整样式，使li垂直居中*/
	    
	    /*分页功能,默认显示第一条*/
	    page_html = '<span><em class="element">1</em>/<em class="denominator">'+denominator+'</em>页，共<em class="denominator">'+denominator+'</em>页，</span><span><a href="javascript:void(0);" data-flag="index">首页</a> <a href="javascript:void(0);" data-flag="prev">上一页</a> <a href="javascript:void(0);" data-flag="next">下一页</a></span>';
	    $page.html(page_html);
	    showPage(1);
	    var $ele = $page.find('.element');
	    /*绑定单选按钮事件,默认选中第一条*/
	    $radio.on('click', function(event) {
	      var $this = $(this);
	      $detail.hide();
	      $this.parents('dt').next('dd').show();
	    });
	    $radio.eq(0).trigger('click');
	    /*绑定分页按钮*/
	    $page.on('click', 'a', function(event) {
	      var $this = $(this),
	          flag = $this.attr('data-flag');
	      switch(flag){
	        case 'index':
	          $ele.text(1);
	          showPage(1);
	          break;
	        case 'next':
	          var index = parseInt($ele.text()),
	              next = null;
	          if (index < denominator) {
	            next = index+1;
	            showPage(next);
	            $ele.text(next);
	          }
	          break;
	        case 'prev':
	          var index = parseInt($ele.text()),
	              prev = null;
	          if (index > 1) {
	            prev = index-1;
	            showPage(prev);
	            $ele.text(prev);
	          }
	          break;
	      }
	    });
	    /*显示第几页*/
	    function showPage(count){// 0,1,2  3,4,5  ,6,7,8
	      var count = count,
	          range = [count*3-3,count*3-1];
	      $inforbox.each(function(index, val) {
	         var $this = $(this);
	         if (range[0] <= index && index <= range[1]) {
	           $this.show();
	         }else{
	            $this.hide().next('dd').hide();
	         }
	      });
	      /*原先选中的状态还是为选中*/
	      $radio.each(function(index, val) {
	        var $this = $(this),
	            $prarent = $this.parents('.product_inforbox'),
	            index = $inforbox.index($prarent);
	          if (range[0] <= index && index <= range[1]) {
	             if ($this.prop('checked')) {
	              $this.parents('dt').next('dd').show();
	             }
	          };
	      });
	    }
	  }
	});
	dialog.size('1045px','480px')
	dialog.position('50%','50%')//重新定位
}


//弹出框去支付   
function gotoPay(goodsId,useYear,userNum,orderId,userId,shoppingCartId){
	
	$.ajax({
		type:"POST",
		url:"/buy/checkIsContain",
		async:false,
		data:{
			goodsId:goodsId,
			orderId:orderId 
		},
		success:function(data){
			if(data.isContain){
				var newOrder = data.newOrder;
				if(newOrder.orderState == 0){
					BSTYUN.dialog.warn("您所选择的商品内已包含您即将购买的商品，如子产品中未出现您所购买的商品，请到<a href='/consume/order/manage' style='color: red;'>订单管理</a>界面进行付款完成购买操作！");
				}else{
					if(newOrder.isDredge == 0){
						BSTYUN.dialog.warn("您所选择的商品内已包含您准备购买的商品，如子产品中未出现您所购买的商品，请到<a href='/consume/order/manage' style='color: red;'>订单管理</a>界面进行开通！");
					}else{
						BSTYUN.dialog.warn("您所选择的商品内已包含您准备购买的商品，如需继续使用，请到<a href='/myservice/order/upgradeManage' style='color: red;'>我的服务</a>进行升级或者续费！");
					}
				}
				
			}else{
				location.href = "/buy/cartToCheck/"+goodsId+"/"+useYear+"/"+userNum+"/"+userId+"/"+shoppingCartId;
			}
		}
	})
}


//购物车  单条删除
function deleteShoppingCart(shoppingCartId,userId){
	var shoppingCartId = shoppingCartId;
	BSTYUN.dialog.confirm('确定删除该条数据？',function(){
		$.ajax({
			type:"GET",
			url:"/buy/deleteShoppingCartByShoppingCartId/" + shoppingCartId,
			async:false,
			success:function(response,data){
				if(data == "success"){
					$('#sc'+shoppingCartId).remove();
					countAll();
					resetTable();
					BSTYUN.dialog.ok("删除成功！");
				}
			}
		})
	});
}

//购物车  批量删除
function deleteShoppingCarts(){
	var _shoppingCartList = "";
	var checkboxList = $("input[name='checkbox']");
	var shoppingCartId = $("input[name='shoppingCartId']");
	var userId = $("input[name='userId']");
	var shoppingCartList = $('input[name="shoppingCartId"]');
	for(var i=0;i<shoppingCartList.length;i++){
		if(checkboxList[i].checked == true) {
			_shoppingCartList += ",";
			_shoppingCartList += shoppingCartId[i].value;
		}
	}
	_shoppingCartList = _shoppingCartList.substr(1);
	
	if(_shoppingCartList == "") return BSTYUN.dialog.warn("请选择一条记录！");
	BSTYUN.dialog.confirm('确定批量删除这些数据？',function(){
		$.ajax({
			type:"GET",
			url:"/buy/deleteShoppingCartsByShoppingCartId/" + _shoppingCartList,
			async:false,
			success:function(response,data){
				if(data == "success"){
					
					var scList = _shoppingCartList.split(",");
					for(var i=0;i<scList.length;i++){
						$('#sc'+scList[i]).remove();
					}
					countAll();
					resetTable();
					BSTYUN.dialog.ok("批量删除成功！");
				}
			}
		})
	});
}

//重置table
function resetTable(){
	var shoppingCartIds = $("input[name='shoppingCartId']");
	if(shoppingCartIds.length == 0){
		var $checkall = $(".checkboxAll");
		$checkall.eq(0).prop("checked",false);
		$checkall.eq(1).prop("checked",false);
		var $tbody = $("#shoppingCartTable tbody");
		$tr = '<tr><td colspan="8">暂无数据，请添加过商品后再查看！</td></tr>';
		$tbody.append($tr);
	}
}

function getYear(str){
	var reg = /\d+/g,
		result = str.match(reg);
	return {
		year: result[0],
		month: result[1],
		day: result[2]
	}
}
